﻿using System.Web;
using System.Web.SessionState;
using Token.Piker.Core.Model;
using Token.Piker.Common;

namespace Token.Piker.Core.Security
{
    /// <summary>
    ///BaseHandler 的摘要说明
    /// </summary>
    public class BaseHandler : IHttpHandler, IRequiresSessionState
    {

        #region 成员
        /// <summary>
        /// 当前上下文
        /// </summary>
        private HttpContext _context;
        public HttpContext Context
        {
            get { return _context; }
            set { _context = value; }
        }

        /// <summary>
        /// 当前登录用户
        /// </summary>
        private AbstractUser user;
        public AbstractUser CurrentUser
        {
            get { return user; }
            set { user = value; }
        }

        #endregion

        
        #region IHttpHandler接口实现
        public virtual void ProcessRequest(HttpContext context)
        {
            // 上下文设置 
            this.Context = context;

            //当前用户(继承此类的Handler直接用CurrentUser获取当前用户)
            if (Context.Session[GlobalConstants.PIKER_USER_ID] != null)
            {
                string userID = Context.Session[GlobalConstants.PIKER_USER_ID].ToString();
                CurrentUser = new AbstractUser(userID);
                CurrentUser.Username = Context.Session[GlobalConstants.PIKER_USER_NAME].ToString();
                CurrentUser.Role = AbstractUser.ERole.已验证;
            }
            else
            {
                CurrentUser = null;
            }
        }

        #region 验证功能

        /// <summary>
        /// 验证是否有权限,只验证角色
        /// </summary>
        /// <param name="desiredRole">允许的角色</param>
        /// <returns>验证结果</returns>
        public bool HasRight(AbstractUser.ERole desiredRole)
        {
            //权限管理器
            IAuthzManager authzMgr = AuthzManagerFactory.Instance();

            EAuthenticateResult result = authzMgr.Validate(desiredRole);

            if (result == EAuthenticateResult.Passed)
                return true;
            else
                return false;

        }

        #endregion


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        #endregion
    }
}